# coding=utf-8
# Create your views here.

"""
copyright (c) 2009, paketka@gmail.com et. al
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

    * Neither the name of the <ORGANIZATION> nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import base64
import urllib
import httplib
import libxml2
import locale
import re
import md5

from django.http import HttpResponse, Http404
from settings import MEDIA_URL
from utils.fetcher import fixStr
from justice.models import *


PROXY_URL = ''
JUSTICE_URL = 'www.justice.cz'
MAP_URL='http://maps.google.com/maps?f=q&hl=cs&q=%s&ie=UTF8&z=16'

def addCSS(head):
    cssNodes = head.xpathEval('//link')
    for node in cssNodes:
        node.unlinkNode()

    styles = [
        '/css/reset.css',
        '/css/style.css',
        '/css/jquery-ui-themeroller.css',
    ]
    for s in styles:
        node = libxml2.newNode('link')
        node.setProp('rel', 'stylesheet')
        node.setProp('href', MEDIA_URL + '/css/reset.css')
        head.addChild(node)

    return


def getAuthToken(name):
    name = name.replace('\xc2\xa0', '')
    name = name.replace(' ', '')
    name = name.replace('\t', '')
    hash = md5.md5(name)
    hash.update(HashKey.retrieve_key())
    return hash.hexdigest()
        

def fetchRegisterByName(name, surname, birthDate):
    def makeNameUrls(node):
        namePattern = re.compile(u'.*Jméno:.*', re.U)
        node = node.get_children()

        if node != None and namePattern.match(node.get_content()) != None:
            node = node.get_next()
            if node != None:
                pattern = re.compile(r'(.*\.\s+)*(?P<name>[^.]+)(\s+.*\.)*', re.U)
                match = pattern.match(node.get_content())
                if match != None:
                    urlParm = match.group('name').strip('\t \f\b\v\r\a\n\xc2\xa0')
                    newNode = libxml2.newNode('a')
                    n = node.get_children()
                    n.unlinkNode()
                    urlParm = urlParm.replace('\xc2\xa0', ' ')
                    name, surname = urlParm.split()
                    print '%s %s' % (name, surname)
                    url = PROXY_URL + '/justice/osoba/%s/%s/%s' % (
                                                            urllib.quote(name),
                                                            urllib.quote(surname),
                                                            getAuthToken(urlParm)
                                                        )
                    newNode.setProp('href', url)
                    newNode.addChild(n)
                    node.addChild(newNode)

    
    def makeAddressUrls(node):
        pattern = re.compile(r'.*Adresa:.*', re.U)
        node = node.get_children()

        if node != None and pattern.match(node.get_content()) != None:
            node = node.get_next()
            if node != None:
                urlParm = node.get_content()
                if urlParm != None:
                    newNode = libxml2.newNode('a')
                    n = node.get_children()
                    n.unlinkNode()
                    newNode.setProp('href', MAP_URL % urllib.quote(urlParm))
                    newNode.addChild(n)
                    node.addChild(newNode)


    def makeListUrls(node):
        listPattern = re.compile(r'.*[vV]ýpis.*', re.U)

        if listPattern.match(node.get_content()) != None:
            href = node.hasProp('href')
            if href != None:
                hrefVal = href.getContent()
                href.setContent('%s/justice/plainProxy/%s' % (PROXY_URL, base64.urlsafe_b64encode(hrefVal)))


    conn = httplib.HTTPConnection(JUSTICE_URL)
    localPath = '/xqw/xervlet/insl/index?sysinf.@typ=or&sysinf.@typ=or&sysinf.@strana=searchResults&hledani.@typ=osoba&hledani.podminka.prijmeni=%s&hledani.podminka.jmeno=%s&Image2.x=0&Image2.y=0'
    localPath = localPath % (   urllib.quote(surname.encode('cp1250')),
                                urllib.quote(name.encode('cp1250'))
                            )
    conn.request('GET', localPath)
    resp = conn.getresponse()

    if resp.status == 200:
        htmlPage = resp.read()
        dom = libxml2.htmlReadDoc(htmlPage, '', None, 0)
        root = dom.getRootElement()

        addCSS(root.xpathEval('//head')[0])

        nameNodes = root.xpathEval('//tr')
        linkNodes = root.xpathEval('//tr/td/a')

        for i in nameNodes:
            makeNameUrls(i)
            makeAddressUrls(i)

        for i in linkNodes:
            makeListUrls(i)

        buf = str(dom) 
        dom.freeDoc()

        return buf
    else:
        return resp.read()


def fetchPapers(localPath):
    def makeNameUrls(node):
        namePattern = re.compile(r'.*len.*:.*|.*rady.*:.*|.*edseda.*:.*', re.U)
        nodeContent = node.content

        if namePattern.match(nodeContent) != None:
            child = node.get_children()
            child = child.get_next()
            if child == None:
                child = node.get_children()
            
            """
            Deals with case as follows:
                PhDr., Ph.D. Michaela Hrubá, r.č. 665428/0842
            """
            name = '? N I K D O ?'
            if child.get_content() != None:
                listCotent = child.get_content().split(',')
                titlePattern = re.compile(r'.+\.$')
                for l in listCotent:
                    match = titlePattern.match(l.strip())
                    if match == None:
                        name = l.strip()
                        break

            id = None
            try:
                id = child.get_content().split(',')[1]
            except:
                id = child.get_content().split(',')[0]

            newNode = libxml2.newNode('a')
            pattern = re.compile(r'(.*\.,?\s*)*(?P<name>.*)(\s*.*\.)*', re.U)
            urlParm = pattern.match(name).group('name').strip('\t \f\b\v\r\a\n\xc2\xa0')
            urlParm = urlParm.replace('\xc2\xa0', ' ')
            name = None
            surname = None
            try:
                name, surname = urlParm.split()
            except:
                fixPattern = re.compile(u'(?P<name>.*[a-zěščřžýáéťďň])(?P<address>[A-ZŠČŘŽ].+)', re.U)
                match =fixPattern.match(urlParm)
                if match != None:
                    tmp = match.group('name')
                    name, surname = tmp.split()
                

            if name == None or surname == None:
                return

            url = PROXY_URL + '/justice/osoba/%s/%s/%s' % (
                                                    urllib.quote(name),
                                                    urllib.quote(surname),
                                                    getAuthToken(urlParm)
                                                )
            newNode.setProp('href', url)
            newNode.setContent(name + ' ' + surname)
            child = child.get_children()
            child.addPrevSibling(newNode)
            child.setContent(id)
            


    def makeAddressUrls(node):
        pattern = re.compile(r'.*Sídlo:.*', re.U)
        node = node.get_children()

        if node != None and pattern.match(node.get_content()) != None:
            node = node.get_next()
            if node != None:
                urlParm = node.get_content()
                if urlParm != None:

                    pscStart = urlParm.find('PSČ')
                    if pscStart > 0:
                        urlParm = urlParm[0:pscStart]

                    newNode = libxml2.newNode('a')
                    n = node.get_children()
                    n.unlinkNode()
                    newNode.setProp('href', MAP_URL % urllib.quote(urlParm))
                    newNode.addChild(n)
                    node.addChild(newNode)

            
    conn = httplib.HTTPConnection(JUSTICE_URL)

    conn.request('GET', '/xqw/xervlet/insl/' + localPath)
    resp = conn.getresponse()

    if resp.status == 200:
        htmlPage = resp.read()
        dom = libxml2.htmlReadDoc(htmlPage, '', None, 0)
        root = dom.getRootElement()

        addCSS(root.xpathEval('//head')[0])

        nodes = root.xpathEval('//tr')
        for i in nodes:
            makeNameUrls(i)

        nodes = root.xpathEval('//tr')
        for i in nodes:
            makeAddressUrls(i)

        buf = str(dom) 
        dom.freeDoc()

        return buf 
    else:
        return resp.read()
    

def view_by_person(request, name, surname, key):
    print '%s ? %s' % (key, getAuthToken(name + surname))
    if key != getAuthToken(name + surname):
        raise Http404
    
    htmlStr = fetchRegisterByName(name.title(), surname.title(), '')

    response = HttpResponse(htmlStr)
    response['Content-Type'] = 'text/html; charset=windows-1250'
    return response


def view_by_person_single_parm(request, base64Name):
    locale.setlocale(locale.LC_ALL, 'czech')
    name = base64Name
    list = name.split()
    name = list[0]
    surname = ''

    for i in list[1:]:
        surname += i + ' '

    surname = surname.strip().upper()

    name_cp = name.title()
    surname_cp = surname.title()
    htmlStr = fetchRegisterByName(name_cp, surname_cp, '')
    response = HttpResponse(htmlStr)
    response['Content-Type'] = 'text/html; charset=windows-1250'
    return response


def plain_proxy(request, justiceURL):
    url = base64.decodestring(justiceURL)
    htmlStr = fetchPapers(url.strip())
    response = HttpResponse(htmlStr)
    response['Content-Type'] = 'text/html; charset=windows-1250'
    return response
